package com.sky.demo.excel;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.ListUtils;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.io.*;
import java.util.*;



@Slf4j
public class ExcelUtil{

    @Test
    public void testRead(){
        String fileName = "C:\\Users\\sky\\Desktop\\psbc20221207.xlsx";
        EasyExcel.read(fileName, DemoData.class, new DemoDataListener()).sheet().doReadSync();
    }

    @Test
    public void testWrite(){
        String fileName = "C:\\Users\\sky\\Desktop\\test0001" + System.currentTimeMillis() + ".xlsx";
        EasyExcel.write(fileName, DemoData.class).sheet("模板").doWrite(data());
    }

    @Test
    public void testWrite2() throws IOException {
        String fileName = "C:\\Users\\sky\\Desktop\\test0001" + System.currentTimeMillis() + ".xlsx";
        String fileName2 = "C:\\Users\\sky\\Desktop\\营销账单明细-邮储养老金活动.csv";
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        //1. excel头部数据如何获取
        //2. 怎么写入头部数据
        DemoDataListener demoDataListener = new DemoDataListener();
        List<DemoData> data = EasyExcel.read(fileName2, DemoData.class, demoDataListener).sheet().headRowNumber(0).doReadSync();
        List<List<Object>> dataList = new ArrayList<>();
        for(int i = 0; i < data.size(); i++){
            DemoData d = data.get(i);
            List<Object> da = ListUtils.newArrayList();
            da.add(d.getIssueTime());
            da.add(d.getCostPrice());
            da.add(d.getCouponCode());
            da.add(d.getIssueType());
            da.add(d.getUseStartTime());
            da.add(d.getUseEndTime());
            da.add(d.getPreRecharge());
            da.add(d.getTemplateId());
            if(i == 10){
                da.add("供方商品订单编码");
            }else if(i > 10 && i < data.size() - 3){
                da.add("abc");
            }
            dataList.add(da);
        }
        EasyExcel.write(byteArrayOutputStream).sheet("模板").doWrite(dataList);
        InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        int index;
        byte[] bytes = new byte[1024];
        FileOutputStream downloadFile = new FileOutputStream(fileName);
        while ((index = inputStream.read(bytes)) != -1) {
            downloadFile.write(bytes, 0, index);
            downloadFile.flush();
        }
        inputStream.close();
        downloadFile.close();
    }

    private List<DemoData> data() {
        List<DemoData> list = ListUtils.newArrayList();
        for (int i = 0; i < 10; i++) {
//            DemoData data = new DemoData();
//            data.setCouponName("字符串" + i);
//            data.setCouponCode(UUID.randomUUID().toString().replace("-", ""));
//            data.setCouponPwd(UUID.randomUUID().toString().replace("-", ""));
//            list.add(data);
        }
        return list;
    }
}
